项目需求描述:

公司架构:–总公司(LongCode:1)

​ –子公司A(LongCode:1.1)

​ –孙公司A1(LongCode:1.1.1)

​ –A1孙公司项目(LongCode:1.1.1.1)

​ –孙公司A2(LongCode:1.1.2)

​ –A公司项目(LongCode:1.1.3)

​ –子公司B(LongCode:1.2)

​ –B公司项目(LongCode:1.2.1)

​ –…

要求:汇总每个子公司下所有项目(包括孙公司的项目)信息,层级关系通过LongCode确定。

​ 并且返回多条汇总信息。

解决方案:

Create Proc P_GetCompanyNewSign 
AS
Begin
--判断有没有临时表有的话先删除
if OBJECT_ID('tempdb..#tblTmp') is not null drop table #tblTmp;
--创建存储返回数据的临时表
create table #tblTmp(
Name nvarchar(100),FinishedInvestAmount decimal(30,6),ShortName nvarchar(100),EpsProjLongCode nvarchar(100)
)
--声明临时变量用来存储循环的LongCode
Declare @temp varchar(50)
--声明游标
declare mycursor cursor
--获取需要循环的子公司LongC0de
for(select LongCode from XX where Name = '子公司' )
--开启游标
open mycursor
--获取下一个传给临时变量,相当于for循环中的i变量
fetch next from mycursor into @temp
--假如检索到了数据继续执行
while @@FETCH_STATUS = 0
Begin
--将一个子公司的数据插入临时表
insert into #tblTmp select * from XX where LongCode='1.1'
--获取下一个传给临时变量,相当于for循环中的i变量
fetch next from mycursor into @temp
End
--关闭释放游标
close mycursor
deallocate mycursor
--查询临时表中的结果集
select * from #tblTmp;
--使用完删除临时表
if OBJECT_ID('tempdb..#tblTmp') is not null drop table #tblTmp;
End